package org.common.dto;

import java.util.ArrayList;
import java.util.List;

import org.common.exception.UtilException;

import java.lang.reflect.Field;

public class ExcelDto {
	private String excelFilePath;
	private List<String> fields = new ArrayList<String>();
	private List<List<Object>> data = new ArrayList<List<Object>>();

	public <T> List<T> convertToObj(Class<T> clazz) throws UtilException {
		List<T> result = new ArrayList<T>();

		for (int i = 0; i < data.size(); i++) {
			T obj = null;
			try {
				obj = clazz.newInstance();
			} catch (Exception e) {
				throw new UtilException(String.format("创建[%s]失败", clazz.getName()), e);
			}
			for (String str : fields) {
				try {
					Field objField = clazz.getDeclaredField(str);
					objField.setAccessible(true);
					Object parameter = getData(i, str);
					if (parameter != null)
						objField.set(obj, parameter);
				} catch (Exception e) {
					// throw new UtilException(String.format("未找到[%s]中对应的属性", clazz.getName()), e);
				}
			}
			result.add(obj);
		}
		return result;
	}

	public ExcelDto(List<String> field, List<List<Object>> data) {
		this.setField(field);
		this.setData(data);
	}

	public ExcelDto(List<String> field, List<List<Object>> data, String excelFilePath) {
		this.setField(field);
		this.setData(data);
		this.excelFilePath = excelFilePath;
	}

	public Object getData(int row, String name) {
		int key = -1;
		for (int i = 0; i < fields.size(); i++) {
			if (fields.get(i).equals(name)) {
				key = i;
				break;
			}
		}

		return key == -1 ? "" : data.get(row).get(key);
	}

	public List<String> getField() {
		return fields;
	}

	public void setField(List<String> fields) {
		this.fields = fields;
	}

	public List<List<Object>> getDatas() {
		return data;
	}

	public void setData(List<List<Object>> data) {
		this.data = data;
	}

	public String getExcelFilePath() {
		return excelFilePath;
	}

	public void setExcelFilePath(String excelFilePath) {
		this.excelFilePath = excelFilePath;
	}
}
